#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include "core/core.h"

namespace py = pybind11;

// 将C结构体映射到Python类
PYBIND11_MODULE(core, m) {
    // 动态数组绑定
    py::class_<IntArray>(m, "IntArray")
        .def(py::init<size_t>())
        .def("push", &int_array_push)
        .def("get", &int_array_get)
        .def("size", [](IntArray* arr) { return arr->size; });
    
    // 矩阵绑定
    py::class_<Matrix>(m, "Matrix")
        .def(py::init<size_t, size_t>())
        .def_property_readonly("shape", [](Matrix* mat) {
            return std::make_tuple(mat->rows, mat->cols);
        })
        .def("__getitem__", [](Matrix* mat, std::pair<size_t, size_t> idx) {
            return mat->data[idx.first * mat->cols + idx.second];
        });
    
    // 图像绑定
    py::class_<Image>(m, "Image")
        .def(py::init<uint32_t, uint32_t, uint8_t>())
        .def_property_readonly("shape", [](Image* img) {
            return std::make_tuple(img->height, img->width, img->channels);
        });
    
    // 函数绑定
    m.def("matrix_multiply", &matrix_multiply, "Matrix multiplication");
    m.def("image_grayscale", &image_grayscale, "Convert image to grayscale");
    
    // 提供NumPy互操作
    m.def("numpy_to_matrix", [](py::array_t<double> arr) {
        auto buf = arr.request();
        if (buf.ndim != 2) throw std::runtime_error("Expected 2D array");
        
        Matrix* mat = matrix_create(buf.shape[0], buf.shape[1]);
        memcpy(mat->data, buf.ptr, buf.size * sizeof(double));
        return mat;
    });
    
    m.def("matrix_to_numpy", [](Matrix* mat) {
        return py::array_t<double>(
            {mat->rows, mat->cols},
            {sizeof(double) * mat->cols, sizeof(double)},
            mat->data
        );
    });
}